/*
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \personnelmanage\src\lib\core\http.tsx
 * @Date: 2021-07-09 11:25:54
 * @LastEditTime: 2022-10-12 15:03:18
 */
import _ from 'lodash'
import axios, { AxiosRequestConfig } from 'axios'
import { udConfigProvider } from '..'

/**终端门户测试接口地址 */
let terurl = 'https://weixin.bdconverge.com/api/sync/dealer/info'
 
if (process.env.REACT_APP_ENV == 'prod') {
  /**终端门户正式接口地址 */
  terurl = 'https://jxs.lzlj.com/api/sync/dealer/info'
}

const terminalUrl = terurl;

const httpFactory = {
  create: (config?: AxiosRequestConfig) => {
    const http = axios.create({
      ...config,
      timeout: 1000 * 60 * 2,
    })

    http.interceptors.request.use((value: any) => {
      value = _.extend({}, udConfigProvider.http, value)
      if (value.url.indexOf('http') == 0) {
        value.baseURL = ''
      }
      value = value.requestBeforeSetToken(value)
      if (value.useRpcWrap) {
        value.headers['x-rpc-wrap'] = '1'
      }
      value = value.requestBefore(value)
      return value
    }, error => {
      let func = _.get(error, 'config.errorHandler.request', udConfigProvider.http.errorHandler.request)
      func(error)
      return Promise.reject(error)
    })

    http.interceptors.response.use((res: any) => {
      if (res.status === 200) {
        if (res.config && res.config.responseType === 'arraybuffer') {
          try {
            const data = arraybufferToObject(res.data)
            res.data = data
          } catch (error) {
            return Promise.resolve(res)
          }
        }
        if (res.config.useRpcWrap) {
          if (res.data.code === 200 || res.data.message == 'success') {
            res.originalData = res.data
            res.data = res.data.data
            return Promise.resolve(res)
          } else {
            if (_.isFunction(res.config.errorHandler[res.data.code])) {
              res.config.errorHandler[res.data.code](res)
            } else {
              if (res.config.useBizErrorHandler) {
                res.config.errorTip({ description: res.data.msg })
              }
            }
            return Promise.reject(res)
          }
        }
        return Promise.resolve(res)
      } else {
        res.config.errorTip({ description: res.statusText })
      }
      return Promise.reject(res)
    }, error => {
      if (error.config && error.config.responseType === 'arraybuffer') {
        try {
          const data = arraybufferToObject(error.response.data)
          error.response.data = data
        } catch (error) {
          return Promise.reject(error)
        }
      }
      if (error.config && error.config.useSysErrorHandler) {
        let handler = error.config.errorHandler.other
        if (error.response) {
          if (_.isFunction(error.config.errorHandler[error.response.status])) {
            handler = error.config.errorHandler[error.response.status]
          }
        }
        handler(error)
      }
      return Promise.reject(error)
    })

    return http
  }
}

/**终端门户地址  请求 */
const httpFactorys = {
  create: (config?: AxiosRequestConfig) => {
    const http = axios.create(config)
    http.interceptors.request.use((value: any) => {
      value = _.extend({}, udConfigProvider.http, value)
      value.baseURL = terminalUrl
      if (value.url.indexOf('http') === 0) {
        value.baseURL = ''
      }
      value = value.requestBeforeSetToken(value)
      if (value.useRpcWrap) {
        value.headers['x-rpc-wrap'] = '1'
      }
      value = value.requestBefore(value)
      return value
    }, error => {
      let func = _.get(error, 'config.errorHandler.request', udConfigProvider.http.errorHandler.request)
      func(error)
      return Promise.reject(error)
    })

    http.interceptors.response.use((res: any) => {
      if (res.data.code !== 500) {
        if (res.config.responseType === 'arraybuffer') {
          try {
            const data = arraybufferToObject(res.data)
            res.data = data
          } catch (error) {
            return Promise.resolve(res)
          }
        }
        return Promise.resolve(res)
      }
      res.config.errorTip({ description: res?.data?.message || res?.data?.msg })
      return Promise.reject(res)
    }, error => {
      if (error.config && error.config.responseType === 'arraybuffer') {
        try {
          const data = arraybufferToObject(error.response.data)
          error.response.data = data
        } catch (error) {
          return Promise.reject(error)
        }
      }
      if (error.config && error.config.useSysErrorHandler) {
        let handler = error.config.errorHandler.other
        if (error.response) {
          if (_.isFunction(error.config.errorHandler[error.response.status])) {
            handler = error.config.errorHandler[error.response.status]
          }
        }
        handler(error)
      }
      return Promise.reject(error)
    })
    return http
  }
}

/** ajax 请求对象 */
const http = httpFactory.create()

const https = httpFactorys.create()

export { http, https, httpFactory, httpFactorys }

export function arraybufferToObject(arraybuffer) {
  let uint8: any = new Uint8Array(arraybuffer) // 提取uint8Array
  let fromCharCode = String.fromCharCode(...uint8)
  let resToString = decodeURIComponent(escape(fromCharCode))
  // 不是文件流数据，将转换好的数据重新覆盖
  return JSON.parse(resToString)
}
